package com.game.backend.service.impl.user.account;

import com.game.backend.mapper.UserMapper;
import com.game.backend.model.User;
import com.game.backend.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, String> register(String username, String password, String confirmedPassword) {

        Map<String,String> map = new HashMap<>();
        username = username.trim();
        if(!StringUtils.hasLength(username)){
            map.put("msg","用户名不能为空");
            return map;
        }
        if(!StringUtils.hasLength(password) || !StringUtils.hasLength(confirmedPassword)){
            map.put("msg","密码不能为空");
            return map;
        }
        if(username.length() > 100){
            map.put("msg","用户名长度不能大于100");
            return map;
        }
        if(password.length() > 100 || confirmedPassword.length() > 100){
            map.put("msg","密码长度不能大于100");
            return map;
        }
        if(!password.equals(confirmedPassword)){
            map.put("msg","两次密码不一致");
            return map;
        }
        User user = userMapper.getByUsername(username);
        if(user != null){
            map.put("msg","用户名已存在");
            return map;
        }
        String encodedPassword = passwordEncoder.encode(password);
        int code = userMapper.add(username,encodedPassword);
        if(code == 1){
            map.put("code","1");
            map.put("msg","success");
        }else{
            map.put("msg","添加数据库失败");
        }
        return map;
    }

    @Override
    public Map<String, String> checkUsername(String username) {
        User user = userMapper.getByUsername(username);
        Map<String,String> map = new HashMap<>();
        if(user != null){
            map.put("msg","用户名已存在");
        }else{
            map.put("msg","success");
        }
        return map;
    }
}
